package com.itboye.ihomebank.activity.guanjia;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.me.ActivityZhangHu;
import com.itboye.ihomebank.util.alipay.OrderInfoUtil2_0;
import com.itboye.ihomebank.util.alipay.PayResult;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.BindCardsList;
import com.itboye.ihomebank.bean.PayInfo;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.RongFengsBean;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimeFormat;
import com.itboye.ihomebank.util.WritePassPopupWindow;
import com.itboye.ihomebank.util.WriteYanZhengMaDialog;
import com.itboye.ihomebank.util.WriteYanZhengMaDialog.OnfinishListener;
import com.itboye.ihomebank.web.WebActivity;

import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * 维修支付
 *
 */
public class ActivityXiuLiZhiFu extends BaseOtherActivity implements Observer,
		OnfinishListener {
	View v_statusbar;
	TextView add_shap_title_tv;
	ImageView close_icon;

	ImageView zf_zhifubao, zf_weixin, zf_yinhangka, zf_yue,xiaotong_selectBtn;

	TextView zf_danhao, zf_money, zf_xiangmu, zf_heji, zf_zongjin, go_pay;

	Intent intent;

	String id;
	String type;
	String money;
	private boolean isZfb = true;
	private UserPresenter userPresenter;
	private String uid;
	private PayInfo payInfo;
	private boolean wx;
	private boolean yhk;
	private boolean yue,xiaotong;
	RelativeLayout choose_card;
	private String bankId;
	TextView bank_type, card_type, item_zhanghu_num,txt_xiaotong;
	private TextView editText;
	private WritePassPopupWindow passPopupWindow;
	private EditText pass;
	private String orderCode;
	private CharSequence fenQiCount="";

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.zf_zhifubao:
				choose_card.setVisibility(View.GONE);
				isZfb = true;
				wx = false;
				yue = false;
				yhk = false;
				xiaotong=false;
				zf_zhifubao.setBackgroundResource(R.drawable.select);
				zf_weixin.setBackgroundResource(R.drawable.unselect);
				zf_yinhangka.setBackgroundResource(R.drawable.unselect);
				zf_yue.setBackgroundResource(R.drawable.unselect);
				xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
				break;
			case R.id.zf_weixin:
				choose_card.setVisibility(View.GONE);
				isZfb = false;
				wx = true;
				yue = false;
				yhk = false;
				xiaotong=false;
				zf_zhifubao.setBackgroundResource(R.drawable.unselect);
				zf_weixin.setBackgroundResource(R.drawable.select);
				zf_yinhangka.setBackgroundResource(R.drawable.unselect);
				zf_yue.setBackgroundResource(R.drawable.unselect);
				xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
				break;
			case R.id.xiaotong_selectBtn:
				setXiaoTong();
				break;
			case R.id.go_pay:
				uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
				if (isZfb) {// 支付宝
					userPresenter.payHouse(uid, "repair", id, "6325", "0", "", "0");
				} else if (yue) {// 余额
					passPopupWindow = new WritePassPopupWindow(this, this);
					pass = (EditText) passPopupWindow.getContentView()
							.findViewById(R.id.pass);
					passPopupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
				} else if (yhk) {// 银行卡
					if (bankId == null) {
						ByAlert.alert("请先选择要支付的银行卡");
						return;
					}
					// userPresenter.payHouse(uid, "house_rent", items, "6327", "",
					// "", "0");
				}
				break;
			case R.id.zf_yue:
				isZfb = false;
				wx = false;
				yue = true;
				yhk = false;
				xiaotong=false;
				choose_card.setVisibility(View.GONE);
				zf_yue.setBackgroundResource(R.drawable.select);
				zf_weixin.setBackgroundResource(R.drawable.unselect);
				zf_zhifubao.setBackgroundResource(R.drawable.unselect);
				zf_yinhangka.setBackgroundResource(R.drawable.unselect);
				xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
				break;
			case R.id.zf_yinhangka:
				wx = false;
				isZfb = false;
				yue = false;
				yhk = true;
				xiaotong=false;
				choose_card.setVisibility(View.VISIBLE);
				zf_yinhangka.setBackgroundResource(R.drawable.select);
				zf_weixin.setBackgroundResource(R.drawable.unselect);
				zf_zhifubao.setBackgroundResource(R.drawable.unselect);
				zf_yue.setBackgroundResource(R.drawable.unselect);
				xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
				break;
			case R.id.choose_card:
				Intent intent = new Intent(this, ActivityZhangHu.class);
				intent.putExtra("type", 0);
				startActivityForResult(intent, 101);
				break;
			case R.id.btn_ok:
				String password = pass.getText().toString();
				if (password.equals("")) {
					ByAlert.alert("请输入余额支付密码");
					return;
				}
				userPresenter.yueYanzheng(uid, password);
				passPopupWindow.dismiss();
				break;
			case R.id.btn_cancel:
				passPopupWindow.dismiss();
				break;
			case R.id.close_icon:
				this.finish();
				break;
			default:
				break;
		}
	}

	int position = -1;
	CharSequence[] xiaoTongItems = {"3", "6", "12"};

	private void setXiaoTong() {
		position = -1;
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("选择分期数");
		alert.setSingleChoiceItems(xiaoTongItems, 0, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				position = which;
			}
		});
		alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (position == -1) {
					position = 0;
				}

				fenQiCount = xiaoTongItems[position];
				choose_card.setVisibility(View.GONE);
				isZfb = false;
				wx = false;
				yue = false;
				yhk = false;
				xiaotong=true;
				zf_zhifubao.setBackgroundResource(R.drawable.unselect);
				zf_weixin.setBackgroundResource(R.drawable.unselect);
				zf_yinhangka.setBackgroundResource(R.drawable.unselect);
				zf_yue.setBackgroundResource(R.drawable.unselect);
				xiaotong_selectBtn.setBackgroundResource(R.drawable.select);
				txt_xiaotong.setText("小通分期("+xiaoTongItems[position]+"期)");
			}
		});
		alert.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		alert.create();
		alert.show();

	}

	@Override
	protected int layout_id() {
		return R.layout.activity_xiuli_zhifu;
	}

	@Override
	protected void onInitController() {

	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == 101 && arg1 == 102) {
			BindCardsList bindCardsList = (BindCardsList) arg2
					.getSerializableExtra("model");
			bankId = bindCardsList.getId();
			bank_type.setText(bindCardsList.getBank().get(0));
			card_type.setText(bindCardsList.getBank().get(1));

			String num=bindCardsList.getBankNo();//银行卡号
			if(num.length()>4){
				String s=num.substring(num.length()-4, num.length());//后四位
				String ss=num.substring(0, num.length()-4);//后四位
				StringBuffer sb=new StringBuffer();
				for (int i=0;i<ss.length();i++){
					sb.append("*");
				}
				item_zhanghu_num.setText(sb+s);
			}else{
				item_zhanghu_num.setText(bindCardsList.getBankNo());
			}
		}
	}

	@SuppressLint("NewApi")
	@Override
	protected void onInit() {
		setStatusBarHeight(v_statusbar);
		dialog = new WriteYanZhengMaDialog(this);
		add_shap_title_tv.setText("立即支付");

		intent = this.getIntent();
		if (intent != null) {
			id = intent.getStringExtra("id");
			money = intent.getStringExtra("money");
			type = intent.getStringExtra("type");

		}
		zf_danhao.setText(id);
		zf_money.setText("￥" + money);
		zf_xiangmu.setText(type);
		zf_heji.setText("￥" + money);
		zf_zongjin.setText("￥" + money);
		zf_zhifubao.setBackgroundResource(R.drawable.select);
		zf_weixin.setBackgroundResource(R.drawable.unselect);
		zf_yinhangka.setBackgroundResource(R.drawable.unselect);
		zf_yue.setBackgroundResource(R.drawable.unselect);
		xiaotong_selectBtn.setBackgroundResource(R.drawable.unselect);
		userPresenter = new UserPresenter(this);
	}

	@Override
	protected void onReadIntent(Bundle bundle) {

	}

	WriteYanZhengMaDialog dialog;

	@SuppressLint("NewApi")
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity.getEventType() == UserPresenter.payHouse_success) {
			payInfo = (PayInfo) entity.getData();
			if (isZfb) {
				zfb(payInfo);
			} else if (yhk) {
				dialog.show(getFragmentManager(), "");
				dialog.setCancelable(false);
				userPresenter.rfPay(uid, payInfo.getCode(), bankId);
			}else if(xiaotong){
				Intent intent = new Intent(this, WebActivity.class);
				///ulinkpay/pay/pay_code/(支付号)/pay_nper/(分期期数)
				intent.putExtra("url", NetPublicConstant.URL + "/ulinkpay/pay/pay_code/" + payInfo.getCode() + "/pay_nper/" + fenQiCount.toString());
				startActivity(intent);
//				finish();
			}
		} else if (entity.getEventType() == UserPresenter.payHouse_fail) {
			ByAlert.alert(entity.getData() + "<>");
		} else if (entity.getEventType() == UserPresenter.yzyue_success) {
			userPresenter.payHouse(uid, "repair", id, "6325", "0", "", "0");
			ByAlert.alert(entity.getData());
		} else if (entity.getEventType() == UserPresenter.yzyue_fail) {
			ByAlert.alert(entity.getData());
		} else if (entity.getEventType() == UserPresenter.rfpayyuzhifu_success) {
			RongFengsBean bean = (RongFengsBean) entity.getData();
			orderCode = bean.getOrder_no();
		} else if (entity.getEventType() == UserPresenter.rfpayyuzhifu_fail) {
			ByAlert.alert(entity.getData());
		}else if(entity.getEventType() == UserPresenter.yzrf_success){
			ByAlert.alert(entity.getData());
			finish();
		}else if(entity.getEventType() == UserPresenter.yzrf_fail){
			ByAlert.alert(entity.getData());
		}
	}

	private static final int SDK_PAY_FLAG = 1;

	/**
	 * 支付宝
	 */
	private void zfb(PayInfo bean) {
		/**
		 * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
		 * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
		 * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
		 * orderInfo的获取必须来自服务端；
		 */
		String money = bean.getTotalPrice();
		double m = Double.parseDouble(money) / 100;
		String content = bean.getName();
		String code = bean.getCode();
		Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(SPContants.APPID, m + "", content, code, TimeFormat.getSimData());
		String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
		String sign = OrderInfoUtil2_0.getSign(params, SPContants.RSA_PRIVATE);
		final String orderInfo = orderParam + "&" + sign;
		Runnable payRunnable = new Runnable() {
			@Override
			public void run() {
				PayTask alipay = new PayTask(ActivityXiuLiZhiFu.this);
				Map<String, String> result = alipay.payV2(orderInfo, true);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}



	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case SDK_PAY_FLAG: {

					PayResult payResult = new PayResult((Map<String, String>) msg.obj);
					/**
					 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
					 */
					String resultInfo = payResult.getResult();// 同步返回需要验证的信息
					String resultStatus = payResult.getResultStatus();
					// 判断resultStatus 为9000则代表支付成功
					if (TextUtils.equals(resultStatus, "9000")) {
						// 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
						Toast.makeText(ActivityXiuLiZhiFu.this, "支付成功", Toast.LENGTH_SHORT).show();
						finish();
					} else {
						// 该笔订单真实的支付结果，需要依赖服务端的异步通知。
						Toast.makeText(ActivityXiuLiZhiFu.this, "支付失败", Toast.LENGTH_SHORT).show();
					}
					break;
				}

				default:
					break;
			}
		}

		;
	};
	private String code;

	@Override
	public void getEditText(String edit) {
		// TODO Auto-generated method stub
		code = edit;
		userPresenter.sendRf(orderCode, code);
		dialog.dismiss();
	}

	@SuppressLint("NewApi")
	@Override
	public void cancel() {
		// TODO Auto-generated method stub
		dialog.dismiss();
	}
}
